package com.ysdz.tibetan.tibetanmini.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ysdz.tibetan.tibetanmini.utils.ToolsUtils;
import com.ysdz.tibetan.tibetanmini.wechat.service.WeChatService;
import com.ysdz.tibetan.tibetanminicommons.common.ReturnMsg;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Value("${wx.applet.appId}")
    private String appId;

    @Value("${wx.applet.appSecret}")
    private String appSecret;

    @Override
    public ReturnMsg getWxUserOpenid(String code, String appId, String appSecret) {
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");      // appId 设置
        url.append(appId);
        url.append("&secret=");    // secret 设置
        url.append(appSecret);
        url.append("&js_code=");   // code 设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        Map<String, Object> map = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();  //构建一个Client
            HttpGet get = new HttpGet(url.toString());               //构建一个GET请求
            HttpResponse response = client.execute(get);             //提交GET请求
            HttpEntity result = response.getEntity();                //拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);                             //打印返回的信息
            JSONObject res = JSONObject.parseObject(content);        //把信息封装为json
            //把信息封装到 map
            map = ToolsUtils.parseJSON2Map(res);                     //这个小工具的代码在下面
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "获取OpenId成功！", map);
    }


}
